package com.changxianggu.crawler.cloud.test;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.changxianggu.cloud.crawler.core.WebApplication;
import com.changxianggu.cloud.crawler.core.modules.storage.entity.CxgBook;
import com.changxianggu.cloud.crawler.core.modules.storage.service.ICxgBookService;
import com.changxianggu.cloud.crawler.core.utils.HttpUtil;
import com.changxianggu.cloud.crawler.core.utils.UserAgentUtil;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {WebApplication.class})// 指定启动类
@Slf4j
public class NongYeDaXue {

    @Autowired
    ICxgBookService bookService;

    public static final String COOKIE = "Hm_lvt_be08f31e017d8f4adaf7d4d57e6b4948=1587001193; JSESSIONID=B59B930992FFE649CC44D531C150CFD0; Hm_lpvt_be08f31e017d8f4adaf7d4d57e6b4948=1587456718";
    public static final String REFERER = "http://press.cau.edu.cn/search/index_1.jhtml?keyword=&newstype=%E5%9B%BE%E4%B9%A6";
    public static final String URL_PRE = "http://press.cau.edu.cn";


    @Test
    public void initCrawler() throws Exception {
        doCrawler();
    }

    public void doCrawler() throws Exception {
        int pageNum = 1;
        int totalPage = 522;
        int pageSize = 4;
        for (int i = pageNum; i <= totalPage; i++) {
            String url = "http://press.cau.edu.cn/search/index_" + i + ".jhtml";
            Map<String, Object> parameter = MapUtil.newHashMap(2);
            parameter.put("keyword", "");
            parameter.put("newstype", "图书");
            Map<String, Object> headers = MapUtil.newHashMap(5);
            headers.put("Cookie", COOKIE);
            headers.put("User-Agent", UserAgentUtil.random());
            headers.put("Referer", REFERER);
            String result = HttpUtil.doGet(url, headers, parameter);
            while (result.contains("页面没有找到")) {
                //睡眠2秒继续访问
                Thread.sleep(2000);
                result = HttpUtil.doPost(url, headers);
            }
            if (StrUtil.isNotBlank(result)) {
                Document htmlDoc = Jsoup.parse(result);
                Elements bookContentList = htmlDoc.select("dl");
                if (bookContentList != null && bookContentList.size() > 0) {
                    List<CxgBook> listBook = new ArrayList<>();
                    for (Element element : bookContentList) {
                        CxgBook bookEntity = new CxgBook();
                        CxgBook tempEntity = new CxgBook();

                        Element titleElement = element.select("dt").first();
                        if (titleElement != null) {
                            String text = titleElement.text();
                            bookEntity.setBookName(text);
                            String href = URL_PRE + titleElement.select("a").first().attr("href");
                            String pkId = getNumbers(href);
                            bookEntity.setPkId(pkId);
                        }

                        bookEntity.setIsSync(0);
                        bookEntity.setCreateTime(LocalDateTime.now());
                        bookEntity.setPressName("中国农业大学出版社");
                        bookEntity.setStatus(1);
                        //出版社Id不明
                        bookEntity.setPressId(14);

                        Element detailElement = element.select("a").first();
                        if (detailElement != null) {
                            String href = detailElement.attr("href");
                            String numStr = getNumbers(href);
                            Integer numId = Integer.parseInt(numStr);
                            try {
                                tempEntity = getBookEntity(numId, bookEntity);
                            } catch (Exception e) {
                                tempEntity = bookEntity;
                            }
                        }
                        if (StrUtil.isNotBlank(tempEntity.getBookIsbn())) {
                            listBook.add(tempEntity);
                        }
                    }
                    bookService.saveBatch(listBook);
                    log.info("第" + i + "页数据保存成功");
                    log.warn("--->" + i);
                }
            }
        }
    }

    public CxgBook getBookEntity(Integer numId, CxgBook bookEntity) throws Exception {
        String url = "http://press.cau.edu.cn/ziyuankutushu/" + numId + ".jhtml";
        Map<String, Object> headers = MapUtil.newHashMap(5);
        headers.put("Cookie", COOKIE);
//        String result = HttpUtil.doGet(url, headers, query);
        String result = HttpUtil.doGet(url, headers);
        while (result.contains("页面没有找到")) {
            //睡眠2秒继续访问
            Thread.sleep(2000);
            result = HttpUtil.doPost(url, headers);
        }
        if (StrUtil.isNotBlank(result)) {
            Document htmlDoc = Jsoup.parse(result);
            Element bookContent = htmlDoc.select(".bookdetsil_right").first();
            if (bookContent != null) {
                Element authorElement = bookContent.select(".author_info").first();
                if (authorElement != null) {
                    String author = authorElement.text();
                    bookEntity.setAuthor(author);
                }

                Element isbnElement = bookContent.select("dd").eq(1).first();
                if (isbnElement != null) {
                    String isbn = isbnElement.text().replace("ISBN:", "").replace("-", "");
                    bookEntity.setBookIsbn(isbn);
                }

                Element pubDateElement = bookContent.select("dd").eq(2).first();
                if (pubDateElement != null) {
                    String pubDateStr = pubDateElement.text().replace("出版日期：", "");
                    if (StrUtil.isNotBlank(pubDateStr)) {
                        pubDateStr = pubDateStr + " 00:00:00";
                        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                        LocalDateTime localDateTime = LocalDateTime.parse(pubDateStr, dtf);
                        bookEntity.setPubDate(localDateTime);
                    }
                }

                Element imgElement = bookContent.select(".fm_img").first();
                if (imgElement != null) {
                    String srcStr = imgElement.attr("src");
                    String cover = URL_PRE + srcStr;
                    bookEntity.setCover(cover);
                }

                Element priceElement = bookContent.select(".f14").first();
                if (priceElement != null) {
                    String priceStr = priceElement.text().replace("￥ ", "");
                    if (StrUtil.isNotBlank(priceStr)) {
                        bookEntity.setPrice(new BigDecimal(priceStr));
                    }
                }

                Element digUriElement = bookContent.select(".btn05").first();
                if (digUriElement != null) {
                    String digUriStr = digUriElement.attr("href");
                    if (StrUtil.isNotBlank(digUriStr)) {
                        bookEntity.setDigitalUri(digUriStr);
                    }
                }

                //catalog
                Element catalogElement = bookContent.select("#bt1 div").first();
                if (catalogElement != null) {
                    String catalogStr = catalogElement.text();
                    if (StrUtil.isNotBlank(catalogStr)) {
                        bookEntity.setCatalog(catalogStr);
                    }
                }

                //brief
                Element briefElement = bookContent.select("#bt0 p").first();
                if (briefElement != null) {
                    String briefStr = briefElement.text();
                    if (StrUtil.isNotBlank(briefStr)) {
                        bookEntity.setBrief(briefStr);
                    }
                }

                //courseware_uri
//                String cuUri = "http://press.cau.edu.cn/pagelayout/ptzy.do?releaselibID=";
//                Element cuElement = bookContent.select(".xaizaidianji").first();
//                if (cuElement != null) {
//                    String cuStr = cuElement.attr("href");
//                    if (StrUtil.isNotBlank(cuStr)) {
//                        bookEntity.setCoursewareUri(cuStr);
//                    }
//                }
            }
        }
        return bookEntity;
    }

    /**
     * 判断一个字符串是否都为数字
     *
     * @param strNum
     * @return
     */
    public boolean isDigit(String strNum) {
        Pattern pattern = Pattern.compile("[0-9]{1,}");
        Matcher matcher = pattern.matcher((CharSequence) strNum);
        return matcher.matches();
    }

    /**
     * 截取数字
     *
     * @param content
     * @return
     */
    public String getNumbers(String content) {
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(content);
        while (matcher.find()) {
            return matcher.group(0);
        }
        return "";
    }
}
